package com.dnzx.auth;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.dnzx.framework.convertor.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dnzx.client.IMenuClient;
import com.dnzx.client.IUserClient;
import com.dnzx.model.system.MenuBO;
import com.dnzx.model.system.UserBO;
import com.dnzx.security.JWTUserDetails;

/**
 * <p>springsecurity用户类</p>
 *
 */
@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserClient userClient;
    @Autowired
    private IMenuClient menuClient;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
//        TODO 从缓存获取
    	UserBO userBO = new UserBO();
    	userBO.setMobile(userName);
        userBO = this.userClient.get(userBO);
        if (userBO == null) {
            throw new UsernameNotFoundException("用户不存在" + userName);
        }
        if ("2".equals(userBO.getStatus())) {
            throw new UsernameNotFoundException("用户已禁用" + userName);
        }
        // 获取用户的权限
//        MenuBO resources = this.menuClient.queryTreeByRole(userBO.getRoleId());
//        Set<GrantedAuthority> grantedAuthorities = convertResourceToGrantedAuthority(resources.getSubMenuBOList());
        Set<GrantedAuthority> grantedAuthorities = convertResourceToGrantedAuthority(new ArrayList<MenuBO>());
        return new JWTUserDetails(userBO.getId(), userBO.getMobile(), userBO.getPassword(), true, true, true, true, grantedAuthorities);
    }

    private Set<GrantedAuthority> convertResourceToGrantedAuthority(List<MenuBO> resources) {
        return obtionGrantedAuthorities(ConvertUtils.convertElementPropertyToList(resources, "name"));
    }

    private Set<GrantedAuthority> obtionGrantedAuthorities(List<String> list) {
        Set<GrantedAuthority> set = new HashSet<GrantedAuthority>();
        for (String power : list) {
            set.add(new SimpleGrantedAuthority(power));
        }
        return set;
    }
}
